package com.dji.sample.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * @author yjt
 * @date 2022-10-25
 * @description:
 */
public class DevicePositionAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        if (CollectionUtils.isEmpty(availableTargetNames)) {
            throw new RuntimeException("分片列表不能为空");
        }
        if (shardingValue == null || shardingValue.getValue() == null) {
            throw new RuntimeException("分片键分片建不能为空");
        }
        // 原始表名
        String logicTableName = shardingValue.getLogicTableName();
        int hashCode = shardingValue.getValue().hashCode();

        hashCode = hashCode < 0 ? ~hashCode : hashCode;
        return logicTableName + "_0"+(hashCode ^ hashCode >>> 16) % availableTargetNames.size();
    }
}
